from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for, flash
from flask_login import login_required, current_user
from models import Post, Category, Tag, Comment, User
from extensions import db
from sqlalchemy import desc, func, or_
# 移除角色检查，个人博客只需要登录即可
import logging
from datetime import datetime, timedelta

logger = logging.getLogger('Personal_Blog_System')

# 创建主路由蓝图
main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """首页 - 显示文章列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = current_app.config.get('POSTS_PER_PAGE', 10)  # 每页显示10篇文章
        
        # 获取已发布的文章
        posts = Post.query.filter_by(status='published').order_by(desc(Post.published_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 获取热门文章
        popular_posts = Post.query.filter_by(status='published').order_by(desc(Post.view_count)).limit(5).all()
        
        # 获取分类统计
        categories = Category.query.filter_by(is_active=True).all()
        # 为每个分类添加文章数量统计
        for category in categories:
            category.post_count = Post.query.filter_by(category_id=category.id, status='published').count()
        
        # 获取标签统计
        tags = Tag.query.all()
        
        # 获取管理员信息
        admin_user = User.query.filter_by(role='admin').first()
        
        return render_template('index.html', 
                             posts=posts, 
                             popular_posts=popular_posts,
                             categories=categories,
                             tags=tags,
                             admin_user=admin_user)
    except Exception as e:
        logger.error(f"首页加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/about')
def about():
    """关于页面"""
    try:
        from sqlalchemy import func
        
        # 获取作者信息
        author = User.query.filter_by(role='admin').first()
        
        # 获取博客统计数据
        total_posts = Post.query.filter_by(status='published').count()
        total_views = db.session.query(func.sum(Post.view_count)).scalar() or 0
        total_comments = Comment.query.count()
        total_tags = Tag.query.count()
        
        stats = {
            'total_posts': total_posts,
            'total_views': total_views,
            'total_comments': total_comments,
            'total_tags': total_tags
        }
        
        return render_template('about.html', author=author, stats=stats)
    except Exception as e:
        logger.error(f"关于页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/contact')
def contact():
    """联系页面"""
    return render_template('contact.html')

@main_bp.route('/search')
def search():
    """搜索页面"""
    try:
        query = request.args.get('q', '').strip()
        page = request.args.get('page', 1, type=int)
        per_page = current_app.config.get('POSTS_PER_PAGE', 5)  # 临时改为5条测试分页
        
        posts = None
        total_results = 0
        
        if query:
            # 搜索已发布的文章
            search_query = Post.query.filter_by(status='published').filter(
                or_(
                    Post.title.contains(query),
                    Post.content.contains(query),
                    Post.excerpt.contains(query)
                )
            )
            
            # 分页
            posts = search_query.order_by(desc(Post.published_at)).paginate(
                page=page, per_page=per_page, error_out=False
            )
            total_results = posts.total
            
        return render_template('search.html', 
                             posts=posts, 
                             query=query,
                             total_results=total_results,
                             page_title=f"搜索结果 - {query}" if query else "搜索")
    except Exception as e:
        logger.error(f"搜索页面加载失败: {str(e)}")
        return render_template('error.html', message="搜索失败，请稍后重试")

@main_bp.route('/category/<int:category_id>')
def category_posts(category_id):
    """分类文章列表"""
    try:
        from models import Category, Post
        from sqlalchemy import desc
        
        # 查询分类
        category = Category.query.get(category_id)
        if not category:
            return render_template('error.html', message="分类不存在")
        
        # 查询该分类下的文章
        page = request.args.get('page', 1, type=int)
        per_page = current_app.config.get('POSTS_PER_PAGE', 10)
        
        posts = Post.query.filter_by(
            category_id=category.id,
            status='published'
        ).order_by(desc(Post.published_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return render_template('search.html', 
                             category=category, 
                             posts=posts,
                             query=f"分类: {category.name}",
                             total_results=posts.total,
                             page_title=f"分类: {category.name}")
    except Exception as e:
        logger.error(f"分类页面加载失败: {str(e)}")
        return render_template('error.html', message="分类页面加载失败，请稍后重试")

@main_bp.route('/tag/<int:tag_id>')
def tag_posts(tag_id):
    """标签文章列表"""
    try:
        from models import Tag, Post
        from sqlalchemy import desc
        
        # 查询标签
        tag = Tag.query.get(tag_id)
        if not tag:
            return render_template('error.html', message="标签不存在")
        
        # 查询该标签下的文章
        page = request.args.get('page', 1, type=int)
        per_page = current_app.config.get('POSTS_PER_PAGE', 10)
        
        posts = Post.query.join(Post.tags).filter(
            Tag.id == tag.id,
            Post.status == 'published'
        ).order_by(desc(Post.published_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return render_template('search.html', 
                             tag=tag, 
                             posts=posts,
                             query=f"标签: {tag.name}",
                             total_results=posts.total,
                             page_title=f"标签: {tag.name}")
    except Exception as e:
        logger.error(f"标签页面加载失败: {str(e)}")
        return render_template('error.html', message="标签页面加载失败，请稍后重试")

# 文章详情页路由已删除，使用静态HTML代替

@main_bp.route('/admin')
@login_required
def admin_dashboard():
    """管理后台首页"""
    try:
        from datetime import datetime, timedelta
        from sqlalchemy import func
        
        # 基础统计信息
        total_posts = Post.query.count()
        total_comments = Comment.query.count()
        
        # 计算总浏览量（假设Post模型有view_count字段）
        total_views = db.session.query(func.sum(Post.view_count)).scalar() or 0
        
        # 计算总点赞量（假设Post模型有like_count字段）
        total_likes = db.session.query(func.sum(Post.like_count)).scalar() or 0
        
        # 本月访客量（最近30天）
        thirty_days_ago = datetime.now() - timedelta(days=30)
        monthly_views = db.session.query(func.sum(Post.view_count)).filter(
            Post.created_at >= thirty_days_ago
        ).scalar() or 0
        
        # 计算增长率（与上个月对比）
        sixty_days_ago = datetime.now() - timedelta(days=60)
        last_month_views = db.session.query(func.sum(Post.view_count)).filter(
            Post.created_at >= sixty_days_ago,
            Post.created_at < thirty_days_ago
        ).scalar() or 0
        
        if last_month_views > 0:
            growth_rate = round(((monthly_views - last_month_views) / last_month_views) * 100, 1)
        else:
            growth_rate = 0.0
        
        # 热门文章（按浏览量排序）
        popular_posts = Post.query.filter_by(status='published').order_by(
            desc(Post.view_count)
        ).limit(10).all()
        
        # 为每个文章添加评论数统计
        for post in popular_posts:
            post.comment_count = Comment.query.filter_by(post_id=post.id).count()
        
        # 访客趋势数据（最近6个月）
        visitor_trend_data = []
        visitor_trend_labels = []
        for i in range(6):
            month_start = datetime.now().replace(day=1) - timedelta(days=30*i)
            month_end = month_start + timedelta(days=30)
            
            month_views = db.session.query(func.sum(Post.view_count)).filter(
                Post.created_at >= month_start,
                Post.created_at < month_end
            ).scalar() or 0
            
            visitor_trend_data.append(month_views)
            visitor_trend_labels.append(month_start.strftime('%m月'))
        
        # 反转数组，让最新的月份在右边
        visitor_trend_data.reverse()
        visitor_trend_labels.reverse()
        
        # 分类分布数据
        categories = Category.query.filter_by(is_active=True).all()
        category_data = []
        category_labels = []
        for category in categories:
            post_count = Post.query.filter_by(category_id=category.id, status='published').count()
            if post_count > 0:
                category_data.append(post_count)
                category_labels.append(category.name)
        
        stats = {
            'total_posts': total_posts,
            'total_views': total_views,
            'total_likes': total_likes,
            'total_comments': total_comments,
            'monthly_views': monthly_views,
            'growth_rate': growth_rate,
            'visitor_trend': {
                'labels': visitor_trend_labels,
                'data': visitor_trend_data
            },
            'category_distribution': {
                'labels': category_labels,
                'data': category_data
            }
        }
        
        return render_template('admin/dashboard.html', 
                             stats=stats,
                             popular_posts=popular_posts)
    except Exception as e:
        logger.error(f"管理后台加载失败: {str(e)}")
        return render_template('error.html', message="管理后台加载失败，请稍后重试")

@main_bp.route('/admin/posts')
@login_required
def admin_posts():
    """文章管理列表页面"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = 10
        status = request.args.get('status', '')
        category_id = request.args.get('category', type=int)
        search = request.args.get('search', '')
        
        # 构建查询
        query = Post.query
        
        if status:
            query = query.filter_by(status=status)
        
        if category_id:
            query = query.filter_by(category_id=category_id)
        
        if search:
            query = query.filter(
                or_(
                    Post.title.contains(search),
                    Post.content.contains(search),
                    Post.excerpt.contains(search)
                )
            )
        
        # 排序和分页
        posts = query.order_by(desc(Post.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 获取分类列表
        categories = Category.query.filter_by(is_active=True).all()
        
        return render_template('admin/posts.html', 
                             posts=posts,
                             categories=categories)
    except Exception as e:
        logger.error(f"文章管理页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/posts/new')
@login_required
def admin_new_post():
    """新建文章页面"""
    try:
        # 获取分类列表
        categories = Category.query.filter_by(is_active=True).all()
        
        # 获取现有标签
        existing_tags = Tag.query.all()
        
        return render_template('admin/post_edit.html',
                             categories=categories,
                             existing_tags=existing_tags)
    except Exception as e:
        logger.error(f"新建文章页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/posts/<int:post_id>/edit')
@login_required
def admin_edit_post(post_id):
    """编辑文章页面"""
    try:
        # 获取文章
        post = Post.query.get_or_404(post_id)
        
        # 检查权限（只有作者本人或管理员可以编辑）
        if post.author_id != current_user.id and current_user.role != 'admin':
            return render_template('error.html', message="没有权限编辑此文章"), 403
        
        # 获取分类列表
        categories = Category.query.filter_by(is_active=True).all()
        
        # 获取现有标签
        existing_tags = Tag.query.all()
        
        return render_template('admin/post_edit.html',
                             post=post,
                             categories=categories,
                             existing_tags=existing_tags)
    except Exception as e:
        logger.error(f"编辑文章页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")


@main_bp.route('/admin/categories')
@login_required
def admin_categories():
    """分类管理页面"""
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '', type=str)
        parent_filter = request.args.get('parent_filter', '', type=str)
        
        # 构建查询
        query = Category.query.filter_by(is_active=True)
        
        # 搜索过滤
        if search:
            query = query.filter(
                or_(
                    Category.name.contains(search),
                    Category.description.contains(search)
                )
            )
        
        # 父分类过滤
        if parent_filter == 'top':
            query = query.filter(Category.parent_id.is_(None))
        elif parent_filter:
            query = query.filter(Category.parent_id == parent_filter)
        
        # 排序和分页
        query = query.order_by(Category.sort_order, Category.name)
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        # 获取所有分类用于构建树结构（用于父分类选择）
        all_categories = Category.query.filter_by(is_active=True).order_by(Category.sort_order, Category.name).all()
        
        return render_template('admin/categories.html', 
                             categories=pagination.items,
                             pagination=pagination,
                             all_categories=all_categories,
                             current_page=page,
                             search=search,
                             parent_filter=parent_filter)
    except Exception as e:
        logger.error(f"分类管理页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/tags')
@login_required
def admin_tags():
    """标签管理页面"""
    try:
        # 获取全部标签，按名称排序
        tags = Tag.query.order_by(Tag.name.asc()).all()
        return render_template('admin/tags.html', tags=tags)
    except Exception as e:
        logger.error(f"标签管理页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/profile')
@login_required
def admin_profile():
    """个人资料页面"""
    try:
        return render_template('admin/profile.html')
    except Exception as e:
        logger.error(f"个人资料页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/profile', methods=['POST'])
@login_required
def update_admin_profile():
    """更新个人资料"""
    try:
        data = request.get_json() if request.is_json else request.form
        name = data.get('name')
        email = data.get('email')
        bio = data.get('bio')
        website = data.get('website')
        github = data.get('github')
        twitter = data.get('twitter')
        
        # 更新用户信息
        if name:
            current_user.name = name
        if email and email != current_user.email:
            # 检查邮箱是否已被其他用户使用
            if User.query.filter(User.email == email, User.id != current_user.id).first():
                if request.is_json:
                    return jsonify({'success': False, 'message': '邮箱已被其他用户使用'})
                flash('邮箱已被其他用户使用', 'error')
                return redirect(url_for('main.admin_profile'))
            current_user.email = email
        if bio is not None:
            current_user.bio = bio
        if website is not None:
            current_user.website = website
        if github is not None:
            current_user.github = github
        if twitter is not None:
            current_user.twitter = twitter
        
        db.session.commit()
        
        if request.is_json:
            return jsonify({'success': True, 'message': '个人资料更新成功'})
        flash('个人资料更新成功', 'success')
        return redirect(url_for('main.admin_profile'))
        
    except Exception as e:
        logger.error(f"更新个人资料失败: {str(e)}")
        db.session.rollback()
        if request.is_json:
            return jsonify({'success': False, 'message': '更新失败，请稍后重试'})
        flash('更新失败，请稍后重试', 'error')
        return redirect(url_for('main.admin_profile'))

@main_bp.route('/admin/account')
@login_required
def admin_account():
    """账户设置页面"""
    try:
        return render_template('admin/account.html')
    except Exception as e:
        logger.error(f"账户设置页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/account/password', methods=['POST'])
@login_required
def change_password():
    """修改密码"""
    try:
        data = request.get_json() if request.is_json else request.form
        current_password = data.get('current_password')
        new_password = data.get('new_password')
        confirm_password = data.get('confirm_password')
        
        # 验证当前密码
        if not current_user.check_password(current_password):
            return jsonify({'success': False, 'message': '当前密码错误'})
        
        # 验证新密码
        if len(new_password) < 6:
            return jsonify({'success': False, 'message': '新密码长度至少6位'})
        
        if new_password != confirm_password:
            return jsonify({'success': False, 'message': '两次输入的密码不一致'})
        
        # 更新密码
        current_user.set_password(new_password)
        db.session.commit()
        
        return jsonify({'success': True, 'message': '密码修改成功'})
        
    except Exception as e:
        logger.error(f"修改密码失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '修改失败，请稍后重试'})

@main_bp.route('/admin/account/security', methods=['POST'])
@login_required
def update_security_settings():
    """更新安全设置"""
    try:
        data = request.get_json()
        login_notification = data.get('login_notification', False)
        
        # 这里可以保存到用户设置表或配置表
        # 暂时只返回成功
        return jsonify({'success': True, 'message': '安全设置已保存'})
        
    except Exception as e:
        logger.error(f"更新安全设置失败: {str(e)}")
        return jsonify({'success': False, 'message': '更新失败，请稍后重试'})

@main_bp.route('/admin/account/delete', methods=['DELETE'])
@login_required
def delete_account():
    """删除账户"""
    try:
        # 这里可以添加额外的验证逻辑
        # 比如检查是否有未完成的操作等
        
        # 删除用户
        db.session.delete(current_user)
        db.session.commit()
        
        return jsonify({'success': True, 'message': '账户删除成功'})
        
    except Exception as e:
        logger.error(f"删除账户失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除失败，请稍后重试'})

@main_bp.route('/admin/settings')
@login_required
def admin_settings():
    """系统设置页面"""
    try:
        # 这里可以加载现有的设置（如从数据库/配置表），暂用占位数据
        settings = {
            'site_title': '我的博客',
            'site_subtitle': '记录与分享',
            'site_description': '一个使用 Flask 构建的个人博客',
            'site_logo': '',
            'enable_comments': True,
            'enable_search': True
        }
        return render_template('admin/settings.html', settings=settings)
    except Exception as e:
        logger.error(f"系统设置页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

@main_bp.route('/admin/comments')
@login_required
def admin_comments():
    """评论管理页面"""
    try:
        # 获取所有评论数据
        comments_query = Comment.query.order_by(desc(Comment.created_at)).all()
        
        # 转换为前端需要的格式
        comments = []
        for comment in comments_query:
            comments.append({
                'id': comment.id,
                'content': comment.content,
                'author_name': comment.author_name,
                'author_email': comment.author_email,
                'post_title': comment.post.title if comment.post else '未知文章',
                'status': comment.status,
                'created_at': comment.created_at
            })
        return render_template('admin/comments.html', comments=comments)
    except Exception as e:
        logger.error(f"评论管理页面加载失败: {str(e)}")
        return render_template('error.html', message="页面加载失败，请稍后重试")

## 清理测试/演示路由（已删除对应模板）
